package com.vmove.childtrain.db.dao;

import android.content.Context;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.Where;
import com.vmove.childtrain.db.BaseDao;
import com.vmove.childtrain.db.DatabaseHelper;
import com.vmove.childtrain.db.entity.Light;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

public class LightDao extends BaseDao<Light> {

    public LightDao(Context context) {
        super(context);
    }


    /**
     * 添加灯，如果lightId已经存在，则使用新记录更新
     * @param light
     * @return
     */
    public int addLight(Light light){
        try {
            Light oldLight = getLightByLightId(light.getLightId());
            if (null!=oldLight){
                //记录已经存在，更新
                light.setId(oldLight.getId());
            }
            return daoOpe.createOrUpdate(light).getNumLinesChanged();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 根据查询指定灯号的记录
     * @param lightId
     */
    public Light getLightByLightId(int lightId){
        try {
            List<Light> lights = daoOpe.queryForEq("lightId", lightId);
            if (null!=lights && lights.size()>0){
                return lights.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int deleteLight(int lightId) throws SQLException {
        DeleteBuilder<Light, Integer> deleteBuilder =daoOpe.deleteBuilder();
        Where<Light, Integer> lightId1 = deleteBuilder.where().eq("lightId", lightId);
        return deleteBuilder.delete();
    }

    /**
     * 查询所有，id升序排列
     * @return
     * @throws SQLException
     */
    public List<Light> getAllLights() throws SQLException {
        return daoOpe.queryBuilder().orderBy("id", true).query();
    }

}
